var userService = require('../service/users');

async function connection(io, socket) {
  var session = socket.request.session;
  var userInfo = await userService.getUserById(session.userid);

  var roomid = userInfo.roomid;

  socket.join(roomid, function() {
    console.log('加入房间' + roomid);
  }); // 加入房间
  // socket.leave('some room'); // 离开房间

  // 监听客户端发送的信息
  socket.on("sentToServer", msg => {
    console.log('sentToServer', userInfo.username);
    // io.emit("sendToClient", msg);
    io.to(roomid).emit('sendToClient', msg);
  });

  socket.on('setkeepAlive', msg => {
    io.to(roomid).emit('getkeepAlive', {
      time: Date.now(),
      username: userInfo.username
    });
  })

  // 监听连接断开事件
  socket.on("disconnect", () => {
    console.log("连接已断开...");
  });

  // socket.on('sentToServer-setColor', color => {
  //   // colorMap[socket.id] = color;
  //   // console.log(colorMap);
  // });
}

module.exports = connection;
